package lxyy.ImageDownloader.src.imageDownloader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class ImageManager {

    private Map<String, String> imageMap;

    public ImageManager() {
        // 初始化集合
        imageMap = new HashMap<>();
        // 确保images目录存在
        FileUtils.ensureDirectoryExists("images");
    }

    public boolean downloadImage(String url) {
        try {
            // 从URL中提取文件名
            String fileName = url.substring(url.lastIndexOf("/") + 1);
            if (fileName.isEmpty()) {
                fileName = "image_" + System.currentTimeMillis() + ".jpg";
            }

            String savePath = "images/" + fileName;

            // 下载图片
            FileUtils.saveImage(url, savePath);

            // 将图片信息添加到集合
            imageMap.put(fileName, savePath);

            // 记录日志
            FileUtils.appendLog("Downloaded: " + url + " -> " + savePath);

            System.out.println("图片下载成功，保存路径: " + savePath);
            return true;
        } catch (IOException e) {
            System.out.println("图片下载失败: " + e.getMessage());
            FileUtils.appendLog("Failed to download: " + url + " - " + e.getMessage());
            return false;
        }
    }


    public void listImages() {
        if (imageMap.isEmpty()) {
            System.out.println("暂无已下载的图片");
            return;
        }

        System.out.println("已下载的图片列表:");
        Set<String> imageNames = imageMap.keySet();
        int index = 1;
        for (String name : imageNames) {
            System.out.println(index + ". " + name + " -> " + imageMap.get(name));
            index++;
        }
    }


    public void searchImage(String name) {
        boolean found = false;

        for (Map.Entry<String, String> entry : imageMap.entrySet()) {
            if (entry.getKey().contains(name)) {
                System.out.println("找到图片: " + entry.getKey() + " -> " + entry.getValue());
                found = true;
            }
        }

        if (!found) {
            System.out.println("未找到包含 \"" + name + "\" 的图片");
        }
    }
}
